<template>
    <div class="container py-8">
      <div class="mb-6">
        <div class="d-flex justify-content-between align-items-center">
          <h1 class="display-4">{{ isNewNote ? '新建笔记' : '编辑笔记' }}</h1>
          <button class="btn btn-outline-secondary" @click="goBack">
            <i class="fa fa-arrow-left mr-2"></i>返回
          </button>
        </div>
      </div>
  
      <div class="card shadow-sm">
        <div class="card-body">
          <form @submit.prevent="saveNote">
            <div class="form-group">
              <input
                type="text"
                class="form-control form-control-lg"
                placeholder="输入笔记标题..."
                v-model="note.title"
                required
              >
            </div>
            <div class="form-group">
              <textarea
                class="form-control"
                rows="15"
                placeholder="输入笔记内容..."
                v-model="note.content"
                required
              ></textarea>
            </div>
            <div class="d-flex justify-content-end">
              <button type="submit" class="btn btn-primary">
                <i class="fa fa-save mr-2"></i>{{ isNewNote ? '保存笔记' : '更新笔记' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </template>
  
  <script>
  export default {
    props: ['id'],
    data() {
      return {
        note: {
          id: '',
          title: '',
          content: '',
          timestamp: new Date().toISOString()
        }
      }
    },
    computed: {
      isNewNote() {
        return this.id === 'new'
      }
    },
    methods: {
      async fetchNote() {
        if (this.isNewNote) return
        
        try {
          const response = await this.$axios.get(`/notes/${this.id}`)
          this.note = response.data
        } catch (error) {
          console.error('获取笔记失败:', error)
          this.$toast.error('获取笔记失败')
          this.goBack()
        }
      },
      async saveNote() {
        try {
          if (this.isNewNote) {
            await this.$axios.post('/notes', this.note)
          } else {
            await this.$axios.put(`/notes/${this.id}`, this.note)
          }
          this.$toast.success(this.isNewNote ? '笔记创建成功' : '笔记更新成功')
          this.goBack()
        } catch (error) {
          console.error('保存笔记失败:', error)
          this.$toast.error('保存笔记失败')
        }
      },
      goBack() {
        this.$router.go(-1)
      }
    },
    mounted() {
      this.fetchNote()
    }
  }
  </script>
  
  <style scoped>
  textarea {
    resize: none;
  }
  </style>    